package com.maxdu.labs.stt.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.constants.FriendRequestConstants;
import com.maxdu.labs.stt.models.db.FriendRequestDBHelper;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class MyFriendsActivity extends Activity {

	private TextView noFriendTView;
	private ListView myFriendsListV;
	private List<ParseObject> myFriends;
	
	private ProfilePictureView profilePictureView;
	private TextView userNameView;
	
	private String currentUser;
	private ProgressBar spinner;
	
	private MyFriendsAdapter adapter;
	
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(final Session session, final SessionState state, final Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_see_my_friends);
		
		profilePictureView = (ProfilePictureView) findViewById(R.id.selection_profile_pic);
	    profilePictureView.setCropped(true);
	    
	    noFriendTView = (TextView) findViewById(R.id.no_friend_request_to_display);
	    noFriendTView.setVisibility(View.GONE);
	    
	    userNameView = (TextView) findViewById(R.id.selection_user_name);
	    myFriendsListV = (ListView) findViewById(R.id.list_friends);
	    
	    
	    spinner = (ProgressBar)findViewById(R.id.progressBar1);
	    spinner.setVisibility(View.GONE);
	    
	    uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
        
        myFriends = new ArrayList<ParseObject>();
       
        adapter = new MyFriendsAdapter(getApplicationContext(), R.layout.row_my_friend, myFriends);
		myFriendsListV.setAdapter(adapter);
		
		Session.openActiveSession(this, true, new Session.StatusCallback() {
		    @Override
		    public void call(Session session, SessionState state, Exception exception) {
		        if(session.isOpened()) {
		            Log.w(Constants.LOG_TAG, "FB session opened successfully");
		            makeMeRequest(session);
		        } else {
		        	if(exception != null){
		        		Log.w(Constants.LOG_TAG, "FB session not opened ... " + exception.toString());
		        	}
		        }
		    }
		});
	}

	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    // Set the id for the ProfilePictureView
	                    // view that in turn displays the profile picture.
	                    profilePictureView.setProfileId(user.getId());
	                    // Set the Textview's text to the user's name.
	                    userNameView.setText(user.getName());
	                    currentUser = user.getId();
	                    Log.w(Constants.LOG_TAG,"currentUser ===> " + currentUser);
	            	    GetFriendsTask task = new GetFriendsTask();
	            	    task.execute(user.getId());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
	
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (session != null && session.isOpened()) {
	        // Get the user's data.
	        makeMeRequest(session);
	    }
	}
	
	
	private class GetFriendsTask extends AsyncTask<String, Void, List<ParseObject>> {

	    @Override
		protected void onPreExecute() {
			super.onPreExecute();
			spinner.setVisibility(View.VISIBLE);
		}
		
		@Override
	    protected List<ParseObject> doInBackground(final String... userIds) {

	    	if (userIds != null){
	    		
	    		ParseQuery<ParseObject> queryPart1 = ParseQuery.getQuery(FriendRequestDBHelper.PARSE_DB_TABLENAME_FRIENDREQUESTS);
	    		queryPart1.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_SENDERID, userIds[0]);
	    		queryPart1.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_ACCEPTED, FriendRequestConstants.FRIEND_REQUEST_ACCEPTED);
	    		
	    		ParseQuery<ParseObject> queryPart2 = ParseQuery.getQuery(FriendRequestDBHelper.PARSE_DB_TABLENAME_FRIENDREQUESTS);
	    		queryPart2.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_RECEIVERID, userIds[0]);
	    		queryPart2.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_ACCEPTED, FriendRequestConstants.FRIEND_REQUEST_ACCEPTED);
	    		
	    		List<ParseQuery<ParseObject>> fullQuery = new ArrayList<ParseQuery<ParseObject>>();
	    		fullQuery.add(queryPart1);
	    		fullQuery.add(queryPart2);
	    		
	    		ParseQuery.or(fullQuery).findInBackground(new FindCallback<ParseObject>() {
					@Override
					public void done(List<ParseObject> myFriendsPO, ParseException e) {
	    		        if (e == null) {
	    		        	
	    		        	if(myFriendsPO.size() > 0){
	    		        		for (ParseObject friend : myFriendsPO)
	    		        		{
	    		        			myFriends.add(friend);
	    		        		}
	    		        		Log.d(Constants.LOG_TAG, "we successfully retrieved from Cloud the friends of this user [" + userIds[0] + "]. This user has " + myFriends.size() + " friends.");
	    		        		adapter.notifyDataSetChanged();
	    		        		spinner.setVisibility(View.GONE);
	    		        	}else{
	    		        		Log.d(Constants.LOG_TAG, "This user [" + userIds[0] + "] has no friend");
	    		        		spinner.setVisibility(View.GONE);
	    		        		noFriendTView.setVisibility(View.VISIBLE);
	    		        	}
	    		        	
	    		        } else {
	    		        	Log.w(Constants.LOG_TAG, "we coudln't retrieve from Cloud the friends of this user [" + userIds[0] + "].");
	    		        }
						
					}
	    		});
	    		
	    		return myFriends;
	    	}
	    	return null;
	    }
	}
	
	private class MyFriendsAdapter extends ArrayAdapter<ParseObject>{

		List<ParseObject> _myFriends;
		
		public MyFriendsAdapter(Context context, int resource,
				List<ParseObject> objects) {
			super(context, resource, objects);
			
			_myFriends = objects;
		}
		
		@Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
			
	        View view = convertView;
	        if (view == null) {
	        	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService
	        		      (Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_my_friend, parent,false);
	        }

	        ParseObject friendRequestPO = _myFriends.get(position);
	        
            TextView nameTextV = (TextView) view.findViewById(R.id.friendrequest_name);
            ProfilePictureView profilePictureView = (ProfilePictureView)view.findViewById(R.id.friendrequest_picture);
            
            String friendId = friendRequestPO.getString(FriendRequestDBHelper.PARSE_DB_FIELD_RECEIVERID);
            if(friendId.equals(currentUser)){
            	friendId = friendRequestPO.getString(FriendRequestDBHelper.PARSE_DB_FIELD_SENDERID);
            }
            
            Log.d(Constants.LOG_TAG,"friendId == " + friendId);
            Log.d(Constants.LOG_TAG,"currentUser == " + currentUser);
            
            profilePictureView.setProfileId(friendId);
            
            nameTextV.setText("fake name");
	        
	        return view;
	    }
	}
}
